const app = getApp();
const util = require('../../static/js/util.js');
const {
  phoneExp,
} = require('../../../common/utils/util.js');
Page({
  data: {
    isCode: true,
    version: 3, //兼容未更新小程序版本
  },
  onLoad(opts) {
    this.setData(opts);
    util.request({
      url: 'entry/wxapp/user.authentication.getinfoneed',
      data: {},
      showLoading: true,
      success: (res) => {
        this.setData({
          list: res.list,
          isauth: res.isauth,
          bannerurl: res.bannerurl,
        });
      },
    });
  },
  /**
   *  姓名、编号、手机号、身份证号、性别
   */
  bindIpVal(e) {
    const id = e.currentTarget.dataset.id;
    const m = {};
    m[id] = e.detail.value;
    this.setData(m);
  },
  /**
   *  提交
   */
  submit(e) {
    let data = this.data;
    delete data['list'];
    delete data['isCode'];
    delete data['isauth'];
    delete data['isauthtype'];
    util.request({
      url: 'entry/wxapp/user.authentication.getinfor',
      data,
      success: result => {
        let page = getCurrentPages();
        if (result.isfaceid === 1) {
          wx.showModal({
            title: '提示',
            content: '验证成功，点击下一步操作',
            confirmText: '下一步',
            showCancel: false,
            success: res => {
              if (res.confirm) {
                this.gotoVerify(result.inid);
              }
            }
          })
        } else {
          wx.showToast({
            title: '认证成功',
            icon: 'none',
            make: true,
            duration: 3000,
            success: () => {
              setTimeout(() => {
                if (page.length > 1) {
                  wx.navigateBack();
                } else {
                  wx.reLaunch({
                    url: '/ws_party_const/pages/index/index',
                  });
                }
              }, 500)
            }
          })
        }
      },
    });
  },
  isSendCode: true,
  sendCode() {
    let {
      phone,
      time = 60,
    } = this.data;
    let countDown = {};
    if (phone === '') {
      wx.showToast({
        title: `手机号不能为空`,
        icon: 'none',
      });
      return false;
    }
    if (!phoneExp.mobile.test(phone)) {
      wx.showToast({
        title: '请填写正确手机号码',
        icon: 'none',
      });
      return;
    }
    if (!this.isSendCode) return;
    this.isSendCode = false;
    util.request({
      url: 'entry/wxapp/user.authentication.getcode',
      data: {
        mobile: phone,
      },
      success: (res) => {
        this.setData({
          isCode: false,
        });
        let count = setInterval(() => {
          time = time - 1;
          countDown.time = time;
          if (time === 0) {
            clearInterval(count); // 清除倒计时
            countDown.time = 60; // 设置倒计时时间
            countDown.isCode = true;
          }
          this.setData(countDown);
        }, 1000);
      },
      complete: () => {
        this.isSendCode = true;
      },
    });
  },
  // 人脸核身获取BizToken
  getBizToken(inid) {
    return new Promise(resolve => {
      const options = {
        url: 'tencentcloud/faceid/detectAuth',
        data: {
          extra: JSON.stringify({
            inid: inid
          })
        },
      };
      const success = res => {
        res.data.errno === 0 && resolve({
          token: res.data.data.BizToken || ''
        });
      };
      this.doRequest(options, success);
    })
  },
  doRequest(options, success = null, fail = null) {
    app.util.request({
      ...options,
      success,
      fail,
    });
  },
  // 开始实名认证
  gotoVerify(inid) {
    const that = this;
    this.getBizToken(inid).then(res => {
      wx.startVerify({
        data: {
          token: res.token, // BizToken，每次验证都需要调用DetectAuth接口获取
          // endPath: "" // 可选，如果传入该参数，验证成功或验证失败会跳转到该页面
        },
        success: function(data) {
          console.log('收到验证成功的回调')
          console.log(data);
          // 验身成功后，将结果数据返回后端
          const options = {
            url: 'tencentcloud/faceid/getDetectInfo',
            data: {
              bizToken: data.BizToken,
            },
            method: 'get',
          };
          const success = res => {
            console.log('success=============', res);
            if (res.data.errno === 0) {
              let page = getCurrentPages();
              wx.showToast({
                title: '认证成功',
                icon: 'none',
                mask: true,
                success: () => {
                  setTimeout(() => {
                    if (page.length > 1) {
                      wx.navigateBack();
                    } else {
                      wx.reLaunch({
                        url: '/ws_party_const/pages/index/index',
                      });
                    }
                  }, 500)
                }
              })
            }
          }
          const fail = res => {
            console.log('fail=============', res);
            wx.showModal({
              title: '提示',
              content: res.data.message,
              showCancel: false,
            })
          }
          that.doRequest(options, success, fail);
        },
        fail: function(err) {
          console.log('收到验证失败的回调')
          console.log(err);
          wx.showToast({
            title: '验证失败',
            icon: 'none',
          })
        },
      });
    });
  },
});